<?php

namespace Casher;

use C\L\WebUserController;

class WithdrawController extends WebUserController
{
    public function indexAction()
    {
        $currentPage = $this->request->getQuery('page', 'int', 1);
        $perPage     = $this->request->getQuery('per_page', 'int', 20);
        $state       = $this->request->getQuery('state', 'string', null);

        $userId = $this->uid;

        $builder = $this->modelsManager->createBuilder()
        ->columns(['withdraw_logs.*', 'user_bank.name', 'user_bank.card'])
        ->from(['withdraw_logs' => 'C\M\WithdrawLog'])
        ->join(
            'C\M\UserBank',
            'user_bank.id = withdraw_logs.user_bank_id',
            'user_bank'
        )
        ->andWhere('withdraw_logs.user_id = :user_id:', ['user_id' => $userId])
        ->orderBy('withdraw_logs.id DESC');

        if ($state) {
            $builder = $builder->andWhere('withdraw_logs.state = :state:', ['state' => $state]);
        }

        $pagination = $this->paginationByBuilder($builder, $currentPage, $perPage);

        $items = array_map(function ($item) {
            $data = $item->withdraw_logs->toArray();
            $data['bank'] = [
                'name' => $item->name,
                'card' => $item->card,
            ];
            return $data;
        }, $pagination['items']->toArray());

        $result = array_merge($pagination, compact('items'));

        $this->success($result);
    }

    public function infoAction()
    {
        $this->checkAuth();
        $this->checkCanWithdraw();
        $this->checkPaymentPassword();

        $banks  = $this->s_bank->searchAll(['uid' => $this->uid]);
        $amount = $this->s_user->getValue('money', ['uid' => $this->uid]);

        return $this->success(compact('banks', 'amount'));
    }

    public function applyAction()
    {
        $this->checkAuth();
        $this->checkCanWithdraw();
        $this->checkPaymentPassword();

        $amount          = $this->request->getPost('amount', 'string', 0);
        $paymentPassword = $this->request->getPost('payment_password', 'string', null);
        $userBankId      = $this->request->getPost('user_bank_id', 'int', null);

        $userId = $this->uid;

        try {
            if (!$this->s_user->checkPayPwd($userId, $paymentPassword)) {
                return $this->error('支付密码错误');
            }

            return $this->s_casher_withdraw->apply($userId, $userBankId, $amount)
              ? $this->success('提现申请成功')
              : $this->error($this->message->getSerMsg());
        } catch (\Exception $error) {
            return $this->error($error->getMessage());
        }
    }
}
